package io.renren.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.taglibs.standard.tag.el.sql.SetDataSourceTag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;

import io.renren.entity.Area;
import io.renren.entity.Personnel;
import io.renren.entity.Station;
import io.renren.service.AreaService;
import io.renren.service.StationService;
import io.renren.utils.PageUtils;
import io.renren.utils.R;


/**
 * 
 * 
 * @author zk
 * @email zk13899@163.com
 * @date 2017-06-14 11:35:05
 */
@Controller
@RequestMapping("station")
public class StationController {
	@Autowired
	private StationService stationService;
	@Autowired 
	private AreaService areaService;
	@RequestMapping("/station.html")
	public String list(){
		return "station/station.html";
	}
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("station:list")
	public R list(Integer page, Integer limit,Integer idArea){
		Map<String, Object> map = new HashMap<>();
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);
		map.put("idArea", idArea);
		//查询列表数据
		List<Station> stationList = stationService.queryList(map);
		int total = stationService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(stationList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
	/* 区域列表 */
	@ResponseBody
	@RequestMapping("/area/list")

	public R arealist() {
		Map<String, Object> map = new HashMap<>();
		List<Area> listArea = areaService.queryList(map);

		return R.ok().put("listArea", listArea);
	}

	/**
	 * 信息
	 */
	@ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("station:info")
	public R info(@PathVariable("id") Integer id){
		Station station = stationService.queryObject(id);
		
		return R.ok().put("station", station);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	@RequiresPermissions("station:save")
	public R save(@RequestBody Station station){
		stationService.save(station);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("station:update")
	public R update(@RequestBody Station station){
		stationService.update(station);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("station:delete")
	public R delete(@RequestBody Integer[] ids){
		stationService.deleteBatch(ids);
		
		return R.ok();
	}
	
	//导出数据到excel
    @RequestMapping("/export2")
  	//@SuppressWarnings("deprecation")
  	public String export(HttpServletResponse response) throws Exception{
    	Map<String, Object> map = new HashMap<>();
  		//如果是从数据库里面取数据 userList
  		List<Station> userList = stationService.queryList(map);// 用户集合
  		
  		System.out.println("++++++++++++++++++++++"+userList);
  		/*
  		 * 设置表头：对Excel每列取名(必须根据你取的数据编写)
  		 */
  		String[] tableHeader = { "编号", "所属区域", "基站名称", "坐标x", "左边Y"
  		};
  		/*
  		 * 下面的都可以拷贝不用编写
  		 */
  		short cellNumber = (short) tableHeader.length;// 表的列数
  		HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个excel
  		HSSFCell cell = null; // Excel的列
  		HSSFRow row = null; // Excel的行
  		HSSFCellStyle style = workbook.createCellStyle(); // 设置表头的类型
  		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		HSSFCellStyle style1 = workbook.createCellStyle(); // 设置数据类型
  		style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  		HSSFFont font = workbook.createFont(); // 设置字体
  		HSSFSheet sheet = workbook.createSheet("sheet1"); // 创建一个sheet
  		HSSFHeader header = sheet.getHeader();// 设置sheet的头
  		try {
  			/**
  			 * 根据是否取出数据，设置header信息
  			 * 
  			 */
  			if (userList.size() < 1) {
  				header.setCenter("查无资料");
  			} else {
  				System.out.println("导出表格的尺寸="+userList);
  				header.setCenter("公司表");
  				row = sheet.createRow(0);
  				row.setHeight((short) 400);
  				for (int k = 0; k < cellNumber; k++) {
  					cell = row.createCell(k);// 创建第0行第k列
  					cell.setCellValue(tableHeader[k]);// 设置第0行第k列的值
  					sheet.setColumnWidth(k, 5000);// 设置列的宽度
  					font.setColor(HSSFFont.COLOR_NORMAL); // 设置单元格字体的颜色.
  					font.setFontHeight((short) 200); // 设置单元字体高度
  					style1.setFont(font);// 设置字体风格
  					cell.setCellStyle(style1);
  				}
  				/*
  				 * // 给excel填充数据这里需要编写
  				 */
  				for (int i = 0; i < userList.size(); i++) {
  					Station user = (Station) userList.get(i);// 获取company对象
  					row = sheet.createRow((short) (i + 1));// 创建第i+1行
  					row.setHeight((short) 400);// 设置行高

  					if (user.getCode() != null) {
  						cell = row.createCell(0);// 创建第i+1行第0列
  						cell.setCellValue(user.getCode());// 设置第i+1行第0列的值
  						cell.setCellStyle(style);// 设置风格
  					}
  					if (user.getIdArea() != null) {//自己设置 的联系人不能为空
  						cell = row.createCell(1); // 创建第i+1行第1列
  						cell.setCellValue(user.getIdArea());// 设置第i+1行第1列的值
  						cell.setCellStyle(style); // 设置风格
  					}
  					// 由于下面的和上面的基本相同，就不加注释了
  					if (user.getName() != null) {
  						cell = row.createCell(2);
  						cell.setCellValue(user.getName());
  						cell.setCellStyle(style);
  					}
  					if (user.getPostionX()!= null) {  
  						cell = row.createCell(3);
  						cell.setCellValue(user.getPostionX());
  						cell.setCellStyle(style);
  					}
  					if (user.getPostionY() !=null) {
  						cell = row.createCell(4);
  						cell.setCellValue(user.getPostionY());
  						cell.setCellStyle(style);
  					}
  				}
  			}
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
  		/*
  		 * 下面的可以不用编写，直接拷贝
  		 */
  		
  			OutputStream out = null;// 创建一个输出流对象
  			try {
  				
  				out = response.getOutputStream();//
  				response.setHeader("Content-disposition", "attachment; filename="
  						+ "company.xls");// filename是下载的xls的名，建议最好用英文
  				response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
  				response.setHeader("Pragma", "No-cache");// 设置头
  				response.setHeader("Cache-Control", "no-cache");// 设置头
  				response.setDateHeader("Expires", 0);// 设置日期头
  				workbook.write(out);
  				out.flush();
  				workbook.write(out);
  			} catch (IOException e) {
  				e.printStackTrace();
  			} finally {
  				try {
  					if (out != null) {
  						out.close();
  					}
  				} catch (IOException e) {
  					e.printStackTrace();
  				}
  			}
  			return null;
  			
  	}
    //文件下载
    @RequestMapping("download")    
    public ResponseEntity<byte[]> download() throws IOException {    
        String path="D:\\workspace2\\renren-zxj\\doc\\df.xlsx";  
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }    
}
